//
//  PCPhotoUploadVC.m
//  PhotoCircle
//
//  Created by wujungao on 12/20/15.
//  Copyright © 2015 wujungao. All rights reserved.
//

#import "PCPhotoUploadVC.h"
#import "PCMeStore.h"
#import "GMTipsHelper.h"
#import "PCUserInfoManager.h"
#import "PCUserModel.h"
#import "PCUserLoginViewController.h"
#import "GMString.h"
#import <ImageIO/ImageIO.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "GMHTTPSessionManager.h"

#define INVALIDTOKEN   20000

@interface PCPhotoUploadVC ()

@property (weak, nonatomic) IBOutlet UIView *topView;
@property (weak, nonatomic) IBOutlet UIImageView *imageView;
@property (weak, nonatomic) IBOutlet UIButton *cancelBtn;
@property (weak, nonatomic) IBOutlet UIButton *backBtn;
@property(nonatomic,strong)UIImage *image;
@property(nonatomic,strong)NSDictionary *imageMetaDict;

- (IBAction)cancelBtnAction:(UIButton *)sender;
- (IBAction)backBtnAction:(UIButton *)sender;

@property(nonatomic,strong)NSString *promptMsg;

@end

@implementation PCPhotoUploadVC

#pragma mark - PCPhotoUploadVC method
-(void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    self.navigationController.navigationBar.translucent = NO;
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    [self.navigationController.navigationBar setBarTintColor:[UIColor whiteColor]];

    MCHiddenBottomView();
    MCShowNavBackButton();
    MCShowNavBar();
    MCHiddenPlusBackgroundView();
    MCHiddenTabBar();
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_W, 0.5)];
    lineView.backgroundColor = [UIColor colorWithRed:255/255.0 green:102/255.0 blue:102/255.0 alpha:1.0];
    [self.view addSubview:lineView];
}

-(void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self configImageViewWithImage:self.image];
    [self upLoadImage:self.image withImageMetaData:self.imageMetaDict];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)passImage:(UIImage *)image withImageMetaDat:(NSDictionary *)imageMetaData{
    
    self.image=image;
    self.imageMetaDict=imageMetaData;
}

#pragma mark - config views
-(void)configBtn{
}

-(void)configImageViewWithImage:(UIImage *)image{
    
    self.imageView.contentMode=UIViewContentModeScaleAspectFit;
    self.imageView.image=image;
}

- (IBAction)cancelBtnAction:(UIButton *)sender {
    //cancel upload
    [GMTipsHelper showDismiss];
    [self cancelUploadImage];
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)backBtnAction:(UIButton *)sender {
    //cancel upload
    [GMTipsHelper showDismiss];
    [self cancelUploadImage];
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)upLoadImage:(UIImage *)image withImageMetaData:(NSDictionary *)imageMetaData{
    
    NSString *token=([[PCUserInfoManager  sharedUserInfo] readUserInfo]).userToken;
    if([NSString isEmptyString:token]){
        [self loginPrompt];
        return;
    }
    
    UIImage *newImage=[self compressImageToTargetSize:self.image];
    NSData *compressedImageData = [self compressImageWith:newImage];
    NSData *saveMetaDataImageData=[self saveMetaDataWithImageData:compressedImageData andMetaData:self.imageMetaDict];
    NSDictionary *dictionary = @{@"token":token};
    
    [GMTipsHelper showLoading];
    [[PCMeStore sharedMeStore] upLoadPhotoToAlbum:dictionary image:saveMetaDataImageData successHandler:^(NSInteger responCode){
        if (responCode == API_RESPONSE_OK) {
            [GMTipsHelper showSuccess:@"上传成功"];
            [self performSelector:@selector(popViewController) withObject:nil afterDelay:0.8];;
        }else if(responCode == API_RESPONSE_INVALIDTOKEN){
            // 加载
            [GMTipsHelper showDismiss];
            [self tipAlertView];
        }else{
            [GMTipsHelper showFail:@"上传失败"];
        }
    } errorHandler:^{
        [GMTipsHelper showBadNetwork];
    }];
}

-(void)popViewController
{
    [self backBtnAction:nil];
}

-(void)loginPrompt{
    
    if (iOS(8.0)) {
        
        UIAlertController * cancleAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"请登录" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            //跳转到个人中心
            [self jumpToLogin];
        }];
        
        UIAlertAction *cancleAcion = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [cancleAlert addAction:okAciton];
        [cancleAlert addAction:cancleAcion];
        [self presentViewController:cancleAlert animated:YES completion:^{
            
        }];
        
    }else{
        
        UIAlertView *cancleAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请登录" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        //cancleAlert.tag =CancleTag;
        cancleAlert.delegate = self;
        [cancleAlert show];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (alertView.tag == INVALIDTOKEN) {
        if (buttonIndex == 0) {
            [[PCUserInfoManager sharedUserInfo] cleanLocalUserInfo];
            //跳转到个人中心
            [self jumpToLogin];
        }else{
        }
    }else{
        if (buttonIndex == 0) {
            //跳转到个人中心
            [self jumpToLogin];
        }else{
        }
    }
}

-(void)jumpToLogin{
    
    UIStoryboard *loginS=[UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];;
    PCUserLoginViewController *loginVC=[loginS instantiateViewControllerWithIdentifier:@"PCUserLoginVC"];
    //
    [self.navigationController pushViewController:loginVC animated:YES];
}

-(void)cancelUploadImage{
    
//    [[GMHTTPSessionManager shared] invalidateSessionCancelingTasks:YES];
    [[PCMeStore sharedMeStore].dataTask cancel];
}


-(void)tipAlertView
{
    if (iOS(8.0)) {
        
        UIAlertController * cancleAlert = [UIAlertController alertControllerWithTitle:@"提示" message:@"您的账号已在其他设备登录，是否重新登录?" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAciton = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            [[PCUserInfoManager sharedUserInfo] cleanLocalUserInfo];
            [self jumpToLogin];
        }];
        
        UIAlertAction *cancleAcion = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }];
        [cancleAlert addAction:okAciton];
        [cancleAlert addAction:cancleAcion];
        [self presentViewController:cancleAlert animated:YES completion:^{
        }];
    }else{
        
        UIAlertView *cancleAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"是否删除图片" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
        //cancleAlert.tag =CancleTag;
        cancleAlert.delegate = self;
        cancleAlert.tag = INVALIDTOKEN;
        [cancleAlert show];
    }
}

#pragma mark - image Process
-(NSData *)compressImageWith:(UIImage *)image{
    
    CGFloat compressionQuality=9.0;
    NSData *imageData=UIImageJPEGRepresentation(image, compressionQuality);
    
    if(imageData.length/1024 > 1000){
        
        imageData=UIImageJPEGRepresentation(image, compressionQuality-0.4);
    }
    
    return imageData;
}

-(NSData *)saveMetaDataWithImageData:(NSData *)imageData andMetaData:(NSDictionary *)imageMetaData{
    
    CGImageSourceRef imageSource=CGImageSourceCreateWithData((__bridge CFDataRef)(imageData),NULL);
    CFStringRef UTI = CGImageSourceGetType(imageSource);
    
    NSMutableData *newImageData = [NSMutableData data];
    CGImageDestinationRef destination = CGImageDestinationCreateWithData(( CFMutableDataRef)newImageData, UTI, 1, NULL);
    CGImageDestinationAddImageFromSource(destination, imageSource, 0, ( CFDictionaryRef) imageMetaData);
    BOOL success = CGImageDestinationFinalize(destination);
//    //test
//    CGImageSourceRef newImageSource=CGImageSourceCreateWithData((__bridge CFDataRef)(newImageData),NULL);
//    //test
    return newImageData;
}

-(UIImage *)compressImageToTargetSize:(UIImage *)image{
    
    CGFloat max=1000.0;
    CGSize imageSize=image.size;
    CGFloat ratio=imageSize.width/imageSize.height;
    
    CGFloat newH=ratio>1.0 ? max * ratio : max;
    CGFloat newW=ratio<1.0 ? max * ratio : max;
    
    UIGraphicsBeginImageContext(CGSizeMake(newW, newH));
    [image drawInRect:CGRectMake(0, 0, newW, newH)];
    
    UIImage *newImage=UIGraphicsGetImageFromCurrentImageContext();
    
    return newImage;
}

@end
